<template>
  <div>
    <n-card :bordered="false" class="pt-3 mb-3 proCard">
      <BasicForm @register="register" @submit="handleSubmit" @reset="handleReset">
        <template #statusSlot="{ model, field }">
          <n-input v-model:value="model[field]" />
        </template>
      </BasicForm>
    </n-card>
    <n-card :bordered="false" class="proCard">
      <BasicTable
        :columns="columns"
        :request="loadDataTable"
        :row-key="(row) => row.id"
        ref="basicTableRef"
        :actionColumn="actionColumn"
        @update:checked-row-keys="onCheckedRow"
        :autoScrollX="true"
      >
        <template #tableTitle>
          <n-space>
            <n-button type="primary" @click="handleAdd" v-perm="['sys:${entity?lower_case}:add']">
              <template #icon>
                <n-icon>
                  <PlusOutlined />
                </n-icon>
              </template>
              新建
            </n-button>
            <n-button
              type="error"
              @click="handleDelete"
              :disabled="!rowKeys.length"
              v-perm="['sys:${entity?lower_case}:batchDelete']"
            >
              <template #icon>
                <n-icon>
                  <DeleteOutlined />
                </n-icon>
              </template>
              删除
            </n-button>
          </n-space>
        </template>
      </BasicTable>
    </n-card>
    <editDialog
      ref="createModalRef"
      :${entity?lower_case}Id="${entity?lower_case}Id"
      v-if="editVisible"
      v-model:visible="editVisible"
      @success="reloadTable('noRefresh')"
    />
  </div>
</template>

<script lang="ts" setup>
  import { h, nextTick, reactive, ref, unref } from 'vue';
  import { useMessage, useDialog } from 'naive-ui';
  import { TableAction } from '@/components/Table';
  import { BasicForm, useForm } from '@/components/Form/index';
  import { get${entity}List, ${entity?lower_case}Delete, ${entity?lower_case}BatchDelete } from '@/api/tool/${entity?lower_case}';
  import { columns } from './columns';
  import { PlusOutlined, DeleteOutlined, FormOutlined } from '@vicons/antd';
  import editDialog from './edit.vue';
  import { schemas } from './querySchemas';
  import { renderIcon } from '@/utils';

  /**
   * 定义参数
   */
  const message = useMessage();
  const dialog = useDialog();
  const basicTableRef = ref();
  const createModalRef = ref();
  const editVisible = ref(false);
  const ${entity?lower_case}Id = ref(0);
  const rowKeys = ref([]);

  /**
   * 定义查询参数
   */
  const formParams = reactive({
  <#list table.fields as field>
    <#if field.propertyName != 'id' 
      && field.propertyName != 'createUser' 
      && field.propertyName != 'createTime' 
      && field.propertyName != 'updateUser' 
      && field.propertyName != 'updateTime' 
      && field.propertyName != 'delFlag' 
      && field.propertyName != 'tenantId'
    >
    <#if field.comment?contains('名称')
      || field.comment?contains('标题')
      || field.comment?contains('状态')
      || field.comment?contains('类型')
    >
      ${field.propertyName}: '',
    </#if>
    </#if>
  </#list>
  });

  /**
   * 定义操作栏
   */
  const actionColumn = reactive({
    width: 200,
    title: '操作',
    align: 'center',
    key: 'action',
    fixed: 'right',
    render(record) {
      return h(TableAction as any, {
        style: 'button',
        actions: [
          {
            label: '编辑',
            icon: renderIcon(FormOutlined),
            type: 'info',
            onClick: handleEdit.bind(null, record),
            auth: ['sys:${entity?lower_case}:update'],
          },
          {
            label: '删除',
            icon: renderIcon(DeleteOutlined),
            type: 'error',
            onClick: handleDelete.bind(null, record),
            auth: ['sys:${entity?lower_case}:delete'],
          },
        ],
      });
    },
  });

  /**
   * 加载数据列表
   * @param res 参数
   */
  const loadDataTable = async (res) => {
    rowKeys.value = [];
    const result = await get${entity}List({ ...formParams, ...res });
    return result;
  };

  /**
   * 数据行选择事件
   * @param keys 参数
   */
  function onCheckedRow(keys) {
    rowKeys.value = keys;
  }

  /**
   * 加载数据列表
   * @param noRefresh 参数
   */
  function reloadTable(noRefresh = '') {
    basicTableRef.value.reload(noRefresh ? {} : { pageNo: 1 });
  }

  /**
   * 执行提交表单
   * @param values 参数
   */
  function handleSubmit(values: Recordable) {
    for (const key in formParams) {
      formParams[key] = '';
    }
    for (const key in values) {
      formParams[key] = values[key];
    }
    reloadTable();
  }

  /**
   * 执行重置
   * @param values 参数
   */
  function handleReset(values: Recordable) {
    for (const key in formParams) {
      formParams[key] = '';
    }
    for (const key in values) {
      formParams[key] = values[key];
    }
    reloadTable();
  }

  /**
   * 执行注册
   */
  const [register, {}] = useForm({
    gridProps: { cols: '1 s:1 m:2 l:3 xl:4 2xl:4' },
    labelWidth: 80,
    schemas,
  });

  /**
   * 执行添加
   */
  const handleAdd = async () => {
    ${entity?lower_case}Id.value = 0;
    editVisible.value = true;
    await nextTick();
    createModalRef.value.openModal();
  };

  /**
   * 执行编辑
   */
  async function handleEdit(record: Recordable) {
    ${entity?lower_case}Id.value = record.id;
    editVisible.value = true;
    await nextTick();
    createModalRef.value.openModal();
  }

  /**
   * 执行删除
   * @param id 参数
   */
  async function handleDelete(record) {
    dialog.warning({
      title: '提示',
      content: '确定要删除？',
      positiveText: '确定',
      negativeText: '取消',
      onPositiveClick: async () => {
        record.id ? await ${entity?lower_case}Delete(record.id) : await ${entity?lower_case}BatchDelete(rowKeys.value);
        message.success('删除成功');
        reloadTable();
      },
    });
  }
</script>

<style lang="less" scoped></style>
